package com.wetao.lib_common.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.DialogLifecycleCallback;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.R;
import com.wetao.lib_common.common.ui.Common_LoginActivity;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.net.cookies.CookiesManager;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class DialogXUtil {
    private static CustomDialog mCustomDialog;
    private static WaitDialog mWaitDialog;
    private static boolean mIsShowProgressDialog = false;
    public static boolean mIsShowReloginDialog = false;
    public static boolean mIsShowCustomDialog = false;
    public interface OnDialogXListen {
        void onListenDialogOk();

        void onListenDialogCancel();

        void onListenDialogClose();
    }

    public interface OnRequestDialogXListen{
        void onCancelProgress();
    }

    public static void dismissAll() {
        WaitDialog.dismiss();
        if(mCustomDialog != null && mIsShowCustomDialog) {
            mCustomDialog.dismiss();
            mIsShowCustomDialog = false;
        }
    }

    public static void waitDialogDismiss() {
        WaitDialog.dismiss();
    }

    public static void customDialogDismiss() {
        if(mCustomDialog != null && mIsShowCustomDialog) {
            mCustomDialog.dismiss();
            mIsShowCustomDialog = false;
        }
    }

    public static boolean isWaitDialogShow() {
        //不是很及时反应
        return mWaitDialog == null ? false : mWaitDialog.isShow();
    }
    public static boolean isCustomDialogShow() {
        //不是很及时反应
        //return mCustomDialog == null ? false : mCustomDialog.isShow();
        return mIsShowCustomDialog;
    }

    public static boolean isShowProgressDialog(){
        return mIsShowProgressDialog;
    }

    public static void hideProgressDialog() {
        if(mCustomDialog != null && mIsShowProgressDialog) {
            mIsShowProgressDialog = false;
            mCustomDialog.dismiss();
        }
    }

    public static boolean isIsShowReloginDialog(){
        return mIsShowReloginDialog;
    }

    public static void hideReloginDialog() {
        if(mCustomDialog != null && mIsShowReloginDialog) {
            mIsShowReloginDialog = false;
            mCustomDialog.dismiss();
        }
    }

    public static void waitDialogShow(String msg) {
        mWaitDialog = WaitDialog.show(msg);
    }


    public static void waitDialogDelay(String msg, int delay) {
        /*ThreadUtils.doOnUIThread(new ThreadUtils.UITask() {
            @Override
            public void doOnUI() {*/
                waitDialogShow(msg);
                waitDialogDelay_real(delay);
            //}
        //});
    }

    private static void waitDialogDelay_real(int delay) {
        Observable.timer(delay, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        waitDialogDismiss();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static void requestDialog(String tip, boolean cancelable, final OnRequestDialogXListen requestListen) {
        if(StringUtil.isEmpty(tip)) {
            tip = "正在加载数据...";
        }
        mWaitDialog = WaitDialog.show(tip);
        if(cancelable) {
            mWaitDialog.setCancelable(true);
        }
        mWaitDialog.setDialogLifecycleCallback(new DialogLifecycleCallback<WaitDialog>() {
            @Override
            public void onShow(WaitDialog dialog) {
                super.onShow(dialog);
            }

            @Override
            public void onDismiss(WaitDialog dialog) {
                requestListen.onCancelProgress();
                super.onDismiss(dialog);
            }
        });
    }

    public static void customDialogShow(String tip, final OnDialogXListen onDialogXListen) {
        customDialogShow(tip, "确定", "取消", onDialogXListen);
    }

    public static void customDialogShow(String tip, boolean isOnlyRight, final OnDialogXListen onDialogXListen) {
        customDialogShow(tip, "确定", "取消", isOnlyRight, 0, onDialogXListen);
    }

    public static void customDialogShow(String tip, String rightTip,boolean isOnlyRight, final OnDialogXListen onDialogXListen) {
        customDialogShow(tip,"", rightTip, isOnlyRight, 0, onDialogXListen);
    }

    public static void customDialogShow(String tip, String leftTip, String rightTip, final OnDialogXListen onDialogXListen) {
        customDialogShow(tip, leftTip, rightTip, false, 0, onDialogXListen);
    }

    public static void customDialogShow( String tip, String leftTip, String rightTip, boolean isOnlyRight, final OnDialogXListen onDialogXListen) {
        customDialogShow(tip, leftTip, rightTip, isOnlyRight, 0, onDialogXListen);
    }
    public static void customDialogShow(String tip, String leftTip, String rightTip, boolean isOnlyRight, int iconId, final OnDialogXListen onDialogXListen) {
        if(mIsShowCustomDialog) {
            return;
        }
        mIsShowCustomDialog = true;
        mCustomDialog = CustomDialog.build()
                .setEnterAnimDuration(0)
                .setExitAnimDuration(0)
                .setMaskColor(Color.parseColor("#4D000000"))
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_ok_cancel_tip_2) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                        Button btn_yes = (Button) v.findViewById(R.id.yes_btn);
                        if (!TextUtils.isEmpty(leftTip)) {
                            btn_yes.setText(leftTip);
                        }

                        btn_yes.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                customDialogDismiss();
                                if (null != onDialogXListen) {
                                    onDialogXListen.onListenDialogOk();
                                }
                            }

                        });

                        Button btn_no = (Button) v.findViewById(R.id.no_btn);
                        if (!TextUtils.isEmpty(rightTip)) {
                            btn_no.setText(rightTip);
                        }

                        //btn_no.getBackground().setAlpha(0);

                        btn_no.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                customDialogDismiss();
                                if (null != onDialogXListen) {
                                    onDialogXListen.onListenDialogCancel();
                                }
                            }

                        });

                        TextView tv = (TextView) v.findViewById(R.id.tv);

                        if (!TextUtils.isEmpty(tip)) {
                            tv.setText(tip);
                        }
                        LinearLayout ll_yes_parent = (LinearLayout) v.findViewById(R.id.ll_yes_parent);
                        if(isOnlyRight) {
                            ll_yes_parent.setVisibility(View.GONE);
                        } else {
                            ll_yes_parent.setVisibility(View.VISIBLE);
                        }

                        if(iconId != 0) {
                            ImageView iv_icon = v.findViewById(R.id.iv_icon);
                            iv_icon.setImageResource(iconId);
                        }
                    }
                });
        mCustomDialog.show();
    }


    public static void progressDialog() {
        mIsShowProgressDialog = true;
        mCustomDialog = CustomDialog.build()
                .setEnterAnimDuration(0)
                .setExitAnimDuration(0)
                .setMaskColor(Color.parseColor("#4D000000"))
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_progress) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                    }
                });
        mCustomDialog.show();
    }

    public static void progressDialogSetStyle(String top, String bottom, int type) {
        View v = mCustomDialog.getCustomView();
        if(v == null) {
            return;
        }
        TextView progress_tv_top = v.findViewById(R.id.progress_tv_top);
        TextView progress_tv_bar = v.findViewById(R.id.progress_tv_bar);
        ProgressBar progress_pb_bar = v.findViewById(R.id.progress_pb_bar);
        TextView progress_tv_bottom = v.findViewById(R.id.progress_tv_bottom);
        if(type == 2) {
            if(progress_pb_bar != null) {
                progress_pb_bar.setProgressDrawable(progress_pb_bar.getResources().getDrawable(R.drawable.progress_blu));
            }
            if(progress_tv_bar != null) {
                progress_tv_bar.setTextColor(Color.parseColor("#00A8B2"));
            }
        } else {
            if(progress_pb_bar != null) {
                progress_pb_bar.setProgressDrawable(progress_pb_bar.getResources().getDrawable(R.drawable.progress_red));
            }
            if(progress_tv_bar != null) {
                progress_tv_bar.setTextColor(Color.parseColor("#FF4A55"));
            }
        }
        if(progress_tv_top != null && top != null) {
            progress_tv_top.setText(top);
        }
        if(progress_tv_bottom != null && bottom != null) {
            progress_tv_bottom.setText(bottom);
        }
    }

    public static void progressDialogSetCur(int progress) {
        View v = mCustomDialog.getCustomView();
        if(v != null) {
            TextView progress_tv_bar = v.findViewById(R.id.progress_tv_bar);
            if(progress_tv_bar != null) {
                progress_tv_bar.setText(progress + "%");
            }
            ProgressBar progress_pb_bar = v.findViewById(R.id.progress_pb_bar);
            if(progress_pb_bar != null) {
                progress_pb_bar.setProgress(progress);
            }
        }
    }


    public static void reLoginDialog(Context context, String tips) {
        if(mIsShowReloginDialog) {
            return;
        }
        mIsShowReloginDialog = true;
        LogUtils.e("退出登录弹框");
        //MultiClickUtil.isFastClick();
        mCustomDialog = CustomDialog.build()
                .setEnterAnimDuration(0)
                .setExitAnimDuration(0)
                .setMaskColor(Color.parseColor("#4D000000"))
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_relogin_tip) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                        TextView tv_tip = v.findViewById(R.id.tv_board_exit_tip);
                        tv_tip.setText(tips);
                        Button btn_ok = v.findViewById(R.id.btn_dialog_re_login_ok);
                        btn_ok.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LogUtils.e("退出登录弹框-确定");
                                /*if(!MultiClickUtil.isFastClick()) {
                                    return;
                                }*/
                                mIsShowReloginDialog = false;
                                hideReloginDialog();
                                onConnectionConflict(context);


                                /*Observable.timer(50, TimeUnit.MILLISECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Observer< Long >() {
                                            @Override
                                            public void onSubscribe(Disposable d) {

                                            }

                                            @Override
                                            public void onNext(Long aLong) {
                                                LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                                                onConnectionConflict(context);
                                                mIsShowReloginDialog = false;;
                                            }

                                            @Override
                                            public void onError(Throwable e) {

                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });*/
                            }
                        });
                    }
                });
        mCustomDialog.show();
    }

    //被踢下线处理
    private static void onConnectionConflict(Context context) {
        DBUtils.getInstance(context).close();
        DBUtils.getInstance(context).clear();


        //清除所有Cookies缓存内容
        CookiesManager.clearAllCookies();
        SPUtils.getInstance().put(Constants.HEAD_XTOKEN, "");
        SPUtils.getInstance().put(Constants.USER_ID_KEY, "");
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_OUTLOGIN, null));
        //SPUtils.getInstance().put(Constants.USER_ID_LIST, "");


        /**
         * 退出登录时通知主程序finish
         */
//        BaseEvent base=new BaseEvent();
//        base.setCode(Constants.EVENT_BUS.USER_UPDATE_OUT_LOGIN);
//        EventBus.getDefault().post(base);

        Intent intent = new Intent();
        intent.setClass(context, Common_LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }


    private static Disposable disposable;
    public static void classCommandDialog(String command, String tip,int type, final OnDialogXListen onDialogXListen) {
        if(mIsShowCustomDialog) {
            return;
        }
        mIsShowCustomDialog = true;
        mCustomDialog = CustomDialog.build()
                .setEnterAnimDuration(0)
                .setExitAnimDuration(0)
                .setMaskColor(Color.parseColor("#4D000000"))
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_ok_cancel_tip_3) {
                    @Override
                    public void onBind(final CustomDialog dialog, View view) {
                        Button btn_yes = view.findViewById(R.id.yes_btn);

                        btn_yes.setOnClickListener(v -> {
                            customDialogDismiss();
                            if(null != onDialogXListen){
                                onDialogXListen.onListenDialogOk();
                            }
                        });

                        LinearLayout ll_answer = view.findViewById(R.id.ll_answer);
                        TextView tv_command_content =  view.findViewById(R.id.tv_command_content);
                        TextView tv_content_title=  view.findViewById(R.id.tv_content_title);
                        ImageView iv_class_in = view.findViewById(R.id.iv_class_in);

                        RelativeLayout rl_pick_answer = view.findViewById(R.id.rl_pick_answer);
                        TextView tv_content_timer = view.findViewById(R.id.tv_pick_answer_timer);

                        rl_pick_answer.setOnClickListener(v->{
                            customDialogDismiss();
                            if(null != onDialogXListen){
                                onDialogXListen.onListenDialogOk();
                            }
                        });

                        if (!TextUtils.isEmpty(tip)){
                            iv_class_in.setImageResource(R.drawable.ic_class_small);
                            tv_content_title.setText(tip);
                            tv_content_title.setVisibility(View.VISIBLE);
                        }else {
                            iv_class_in.setImageResource(R.drawable.ic_class_answer);
                            tv_content_title.setVisibility(View.INVISIBLE);
                        }

                        tv_command_content.setText(command);
                        if (type == Constants.TYPE_CLASSIN_PICK_ANSWER){
                            rl_pick_answer.setVisibility(View.VISIBLE);
                            ll_answer.setVisibility(View.GONE);
                            initTimer(tv_content_timer,5);
                        }else {
                            rl_pick_answer.setVisibility(View.GONE);
                            ll_answer.setVisibility(View.VISIBLE);
                        }
                    }
                });
        mCustomDialog.show();
    }

    private static  void initTimer(TextView view, int count) {

        Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .take(count + 1) //设置发送count+1次 因为是count~0秒
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        LogUtils.d("apply"+(count-aLong));
                        return count - aLong; //发送倒计时
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//操作UI要在UI线程
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onComplete() {
                        LogUtils.d("onCompleted: "+System.currentTimeMillis());
                        disposable();
                        customDialogDismiss();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        view.setText(count + "");
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) { //接受到一条就是会操作一次UI
                        LogUtils.d("onNext: "+aLong);
                        view.setText(aLong + "");
                    }
                });
    }

    private  static void disposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }


    public static void popTipShow(String tip, int delay) {
        PopTip.show(tip).autoDismiss(delay);
    }



    public static void releaseDialog() {
        if(mCustomDialog != null) {
            if(mCustomDialog.isShow()) {
                mCustomDialog.dismiss();
            }
            mCustomDialog = null;
        }

        if(mWaitDialog != null) {
            if(mWaitDialog.isShow()) {
                WaitDialog.dismiss();
            }
            mWaitDialog = null;
        }
        mIsShowProgressDialog = false;
        mIsShowReloginDialog = false;
        mIsShowCustomDialog = false;
    }
}
